#include "HomeUi.h"
#include "ui_HomeUi.h"
#include "WidgetHandler.h"
#include "MiscData.h"
#ifdef arm
#include "Mpp.h"
#endif
#include "HintDialog.h"
#include "Database.h"
#include "Medio.h"
#include "ExportDialog.h"
#include "ExportWorker.h"
#include "FileUtility.h"
#include "LogoUtility.h"
#include "AuthorityDialog.h"
#include "Mcu.h"
#include "Fpga.h"
#include <QDateTime>
#include <QFile>
#include "StorageUtility.h"
#include "Setting.h"
#include "Mcu.h"
#include "SensorInfo.h"

HomeUi::HomeUi(QWidget *parent) :
    BaseWidget(parent),
    ui(new Ui::HomeUi)
{
    ui->setupUi(this);
    ui->uiToast->setVisible(false);
    ui->textToast->setVisible(false);
    LogoUtility::getInstance()->addLogoLabel(ui->logo);
   // ui->image->installEventFilter(this);
    m_temperature = new QFile("/sys/devices/virtual/thermal/thermal_zone0/temp");
    g_syncTimer = new QTimer();
    QObject::connect(g_syncTimer, &QTimer::timeout, this, &HomeUi::syncTimerSlot);
    g_syncTimer->start(1000);

    g_toastTimer = new QTimer();
    QObject::connect(g_toastTimer, &QTimer::timeout, this, &HomeUi::toastTimerSlot);
    g_toastTimer->setSingleShot(true);

    g_recordTimer = new QTimer();
    QObject::connect(g_recordTimer, &QTimer::timeout, this, &HomeUi::recordTimerSlot);
    QObject::connect(&SensorInfo::getInstance(), &SensorInfo::sensorTypeChanged, [&](){
        m_sensorType = SensorInfo::getInstance().getSensorType();
        ui->imageRotate_2->setVisible(m_sensorType == 0X69);
        if(m_sensorType == 0X69) {
            RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageZoomIndex = 0;
            on_imageRotate_clicked();
        } else if(m_sensorType == 0X97){
            ui->pushButton->setStyleSheet("background-color: rgb(0, 0, 0);");
            RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageZoomIndex = 5;
            on_imageRotate_clicked();
        } else {
            ui->pushButton->setStyleSheet("background-color: rgb(0, 0, 0);");
        }

        setMaskType();

    });
    ui->externalStorageInfo->setVisible(false);
    syncInternalStorageInfo();
    ui->imageRotate_2->hide();
    QObject::connect(AuthorityDialog::getInstance(), &AuthorityDialog::HomeUi_Export_Signal, this, &HomeUi::HomeUi_Export_Slot);
    on_imageRotate_2_clicked();

}

HomeUi::~HomeUi()  {
    delete ui;
}

void HomeUi::toastTimerSlot() {
    if (RuntimeData::MiscData::getInstance()->g_miscDataInfo.recordState == 0) {
        ui->textToast->setVisible(false);
    }
    ui->uiToast->setVisible(false);

}

void HomeUi::syncTimerSlot() {
    syncInternalStorageInfo();

    ui->label_2->setText(QDateTime::currentDateTimeUtc().toString("yyyy/MM/dd hh:mm:ss"));
    updateTemperature();
    if(flag && (!StorageUtility::getInstance()->isHaveEnoughFreeSize()) ) {
        recordSlot();
        internelStorgeNoEnough();
    }
}

void HomeUi::recordTimerSlot()
{
    g_recordDuration = g_recordDuration.addSecs(1);
    ui->textToast->setText(QString(tr("录像中: %1")).arg(g_recordDuration.toString("HH:mm:ss")));
}

void HomeUi::activate()
{
    int currentApplyPatientNumber = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;
    m_isaction = true;
    syncInternalStorageInfo();
#ifdef arm
    Mpp::getInstance()->startRealtimeImage();
#endif
    if (currentApplyPatientNumber < 0) {
        ui->name->setText(tr("未选择患者"));
        ui->gender->setText("");
        ui->birthday->setText("");
    } else {
        /* 通过number查询 */
        PatientInfo* info = Database::getInstance()->queryPatient(currentApplyPatientNumber);
        if (info->number < 0) {
            qDebug()<<"HomeUi, system error: no fine selected patient";
            return;
        }
        ui->name->setText(info->name);
        ui->gender->setText(QString("%1").arg(info->gender?tr("男"):tr("女")));
        QString age = "%1";
        if(info->age<=0) {
            age = "???";
        } else {
            age = age.arg(info->age);
        }
        ui->birthday->setText(age);
    }
    setMaskType();
    ui->pushButton_2->setVisible(RuntimeData::MiscData::getInstance()->g_miscDataInfo.openCrossLine);
}

void HomeUi::inactivate()
{
    Mpp::getInstance()->stopRealtimeImage();
}

void HomeUi::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;

    default:
        break;
    }
}

void HomeUi::on_imageSetting_clicked()
{

        Mcu::getInstance()->touchSoundBeepMessage();
        WidgetHandler::getInstance()->displayWidget(ImageSettingUi_Id);
        m_isaction = false;

}

void HomeUi::on_systemSetting_clicked()
{
    if(m_allowSwitch){
        Mcu::getInstance()->touchSoundBeepMessage();
        WidgetHandler::getInstance()->displayWidget(SystemSettingUi_Id);
        m_isaction = false;
    }
}

void HomeUi::on_addPatient_clicked()
{
    if(m_allowSwitch){
        Mcu::getInstance()->touchSoundBeepMessage();
        WidgetHandler::getInstance()->displayWidget(AddPatientUi_Id);
        m_isaction = false;
    }
}

void HomeUi::on_queryPatient_clicked()
{
    if(m_allowSwitch){
        Mcu::getInstance()->touchSoundBeepMessage();
        WidgetHandler::getInstance()->displayWidget(QueryPatientUi_Id);
        m_isaction = false;
    }
}

void HomeUi::on_imagePlayback_clicked()
{
    if(m_allowSwitch){
        Mcu::getInstance()->touchSoundBeepMessage();

        int currentApplyPatientNumber = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;

        if (currentApplyPatientNumber < 0) {
            HintDialog::getInstance()->setInfo(tr("请先选择或新建一个患者!"), HintDialogType_Hint);
            HintDialog::getInstance()->exec();
            return;
        }
        RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber = currentApplyPatientNumber;
        RuntimeData::MiscData::getInstance()->g_miscDataInfo.patientInfoEntryType = 0;
        WidgetHandler::getInstance()->displayWidget(PatientInfoUi_Id);
        m_isaction = false;
    }
}

void HomeUi::on_imageRotate_clicked()
{
    if(true){
        Mcu::getInstance()->touchSoundBeepMessage();

        RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageZoomIndex++;
        if (RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageZoomIndex > 3)
            RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageZoomIndex = 0;

        int index = RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageZoomIndex;
        /* set fpga */
        setFpga[ImageZoom_Index](index, 0);
        switch (index) {
        case 0:
            ui->imageRotate->setText("X1");
            break;

        case 1:
            ui->imageRotate->setText("X2");
            break;

        case 2:
            ui->imageRotate->setText("X3");
            break;

        case 3:
            ui->imageRotate->setText("X4");
            break;
        }
    }
}

/* 拍照 */
void HomeUi::takePhotoSlot()
{
    if(!StorageUtility::getInstance()->isHaveEnoughFreeSize()){
        internelStorgeNoEnough();
        return;
    }
    if(!m_isaction)return;
    int currentApplyPatientNumber = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;

    if (currentApplyPatientNumber < 0) {
        HintDialog::getInstance()->setInfo(tr("请先选择一个患者!"), HintDialogType_Hint);
        HintDialog::getInstance()->exec();
        return;
    }

    QString imagePath = Medio::getInstance()->getCurrentPatientNextImagePath();
    qDebug()<<"new imagePath = "<<imagePath;
#ifdef arm
    Mpp::getInstance()->takePhotoByRealtimeImage({imagePath});
#endif
    g_syncType = 0;
    g_syncTimer->start(1000);
    updateToastSlot(9);
}

/* 录像 */
void HomeUi::recordSlot()
{

    if(!m_isaction)return;
    int currentApplyPatientNumber = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;
    int state = RuntimeData::MiscData::getInstance()->g_miscDataInfo.imageFreezeState;

    if (currentApplyPatientNumber < 0) {
        HintDialog::getInstance()->setInfo(tr("请先选择一个患者!"), HintDialogType_Hint);
        HintDialog::getInstance()->exec();
        return;
    }

//    if (state == 1) {
//        HintDialog::getInstance()->setInfo(tr("图像已冻结，无法录像!"), HintDialogType_Hint);
//        HintDialog::getInstance()->exec();
//        return;
//    }

    if (flag == 0) {
        if(!StorageUtility::getInstance()->isHaveEnoughFreeSize()){
            internelStorgeNoEnough();
            return;
        }
        flag = 1;
        QString path = Medio::getInstance()->getCurrentPatientNextVideoPath();
        QString videoMp4 = path;
        videoMp4.append(".mp4");
        QString videoPng = path;
        videoPng.append(".jpg");

        qDebug()<<"new videoMp4 = "<<videoMp4;
        qDebug()<<"new videoJpg = "<<videoPng;
#ifdef arm
        Mpp::getInstance()->takePhotoByRealtimeImage({videoPng});
        Mpp::getInstance()->startRealtimeImageRecord({videoMp4});
#endif
        g_syncType = 1;
        g_syncTimer->start(1000);

        g_recordDuration.setHMS(0, 0, 0);
        g_recordTimer->start(1000);
        ui->textToast->setText(tr("准备录像中..."));
        ui->textToast->setVisible(true);
        RuntimeData::MiscData::getInstance()->g_miscDataInfo.recordState = flag;
        m_allowSwitch = false;
    } else {
        flag = 0;
        RuntimeData::MiscData::getInstance()->g_miscDataInfo.recordState = flag;
#ifdef arm
        Mpp::getInstance()->stopRealtimeImageRecord();
#endif
        updateToastSlot(3);
        m_allowSwitch = true;
    }
}

const QMap<int, const char*> m_mirrorTypeMap{
    {0, QT_TRANSLATE_NOOP("QObject", "默认")},
    {1, QT_TRANSLATE_NOOP("QObject", "自定义1")},
    {2, QT_TRANSLATE_NOOP("QObject", "自定义2")},
    {3, QT_TRANSLATE_NOOP("QObject", "宫腔镜")},
    {4, QT_TRANSLATE_NOOP("QObject", "膀胱镜")},
    {5, QT_TRANSLATE_NOOP("QObject", "肾盂镜")},
};

/*  type: 和键值类型一致*/
void HomeUi::updateToastSlot(int type, int value)
{
    qDebug()<<"toast type = "<<type<<" value = "<<value;
    switch (type) {
    case 1:
    case 2:
        ui->uiToast->setRange(0, 10);
        ui->textToast->setText(QString("x%1").arg(value + 1));
        ui->uiToast->setValue(value + 1);
        ui->uiToast->setVisible(true);
        ui->textToast->setVisible(true);
        break;

    case 3:
        g_recordTimer->stop();
        ui->textToast->setText(tr("正在保存录像..."));
        ui->textToast->setVisible(true);
        break;

    case 9:
        ui->textToast->setText(tr("正在保存照片..."));
        ui->textToast->setVisible(true);
        break;

    case 5:
        on_imageRotate_clicked();
        break;
    case 4:
        if (value == 0) {
            ui->textToast->setText(tr("画面解冻"));
        } else {
            ui->textToast->setText(tr("画面冻结"));
        }
        ui->textToast->setVisible(true);
        break;

    case 6:
        ui->textToast->setText(tr("白平衡执行成功"));
        ui->textToast->setVisible(true);
        break;

    case 7:
        setMaskType();
        ui->textToast->setText(QApplication::translate("QObject",m_mirrorTypeMap.value(value),Q_NULLPTR));
        ui->textToast->setVisible(true);
        break;

    case 8:
        ui->textToast->setText(tr("系统复位"));
        ui->textToast->setVisible(true);
        break;
    }
    g_toastTimer->start(1500);
}

void HomeUi::syncInternalStorageInfo()
{

    ui->progressBar_2->setValue(StorageUtility::getInstance()->internalFreePhotoSize());

    if(StorageUtility::getInstance()->isHaveDisk()) {
       ui->externalStorageInfo->show();
       ui->progressBar->setValue(StorageUtility::getInstance()->externalFreePhotoSize());
    } else {
        ui->externalStorageInfo->hide();
    }
}

void HomeUi::syncExternalStorageInfo() {

}

void HomeUi::updateTemperature() {
    if(!m_temperature)return;
    float cput;
    uint32_t fpagv;
    if(!m_temperature->isOpen()){
       m_temperature->open(QFile::ReadOnly);
    }

    if(m_temperature->isOpen()){
         cput = QString(m_temperature->readLine()).toInt()/1000.0f;
         fpagv = Fpga::getInstance()->readRegister(0x40);
//            int fpgat = QString("%1").arg(fpagv,0,10).toInt();
        ui->label->setText(QString("CPU:%1\nFPGA:%2").arg(cput).arg(fpagv));
    }

    if(cput>=95.0f) {
        if(flag) {
            recordSlot();
        }
        qDebug()<<"system shutdown when temperature = 95";
        Mcu::getInstance()->systemShutdownMessage();
    }

    if(RuntimeData::MiscData::getInstance()->enableTempratureMonitor){
        ui->label->show();
    }else{
        ui->label->hide();
    }
}

void HomeUi::internelStorgeNoEnough() {
    HintDialog::getInstance()->setInfo(tr("空间不足"),HintDialogType_Null);
    HintDialog::getInstance()->show();
}

void HomeUi::setMaskType() {
    auto m_sensorType = SensorInfo::getInstance().getSensorType();
    int mirrorType = RuntimeData::BootSetting::getInstance()->g_bootSettingInfo.currentMirrorType;
    int v = RuntimeData::ImageSetting::getInstance()->g_settingItemValue[mirrorType][10];
    if(m_sensorType == 0x69) {
        if(v == 0) {
            ui->pushButton->setStyleSheet("background-color: rgb(0, 0, 0);"
                                          "border-image: url(:/image/rectMask.png);border:none;");
        } else if( v == 2) {
            ui->pushButton->setStyleSheet("background-color: rgb(0, 0, 0);"
                                          "border-image: url(:/image/roundMask.png);border:none;");
        } else {
            ui->pushButton->setStyleSheet("background-color: rgb(0, 0, 0);"
                                          "border-image: url(:/image/rect45Mask.png);border:none;");
        }
    } else {
        ui->pushButton->setStyleSheet("background-color: rgb(0, 0, 0);border:none;");
    }
}

void HomeUi::on_imageExport_clicked()
{
    if(m_allowSwitch){
        Mcu::getInstance()->touchSoundBeepMessage();

        int userId = RuntimeData::BootSetting::getInstance()->g_bootSettingInfo.currentUserId;

        if (userId < 0) {
            AuthorityDialog::getInstance()->setParent(this);
            AuthorityDialog::getInstance()->setAuthorityType(AuthorityType_HomeUi_Export);
            AuthorityDialog::getInstance()->exec();
            return;
        } else {
            HomeUi_Export_Slot();
        }
    }
}

void HomeUi::HomeUi_Export_Slot()
{
    if(m_allowSwitch){

        int currentSelectPatientNumber = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;
        if (currentSelectPatientNumber < 0) {
            HintDialog::getInstance()->setInfo(tr("请先选择一个患者!"), HintDialogType_Hint);
            HintDialog::getInstance()->exec();
            return;
        }

        if (FileUtility::getInstance()->checkUsbDirExist("/run/media") < 0) {
            HintDialog::getInstance()->setInfo(tr("未找到外部存储设备!"), HintDialogType_Hint);
            HintDialog::getInstance()->exec();
            return;
        }
        ExportWorker::getInstance()->startWork(currentSelectPatientNumber);
        ExportDialog::getInstance()->exec();
    }
}

void HomeUi::on_gohome_clicked()
{   if(m_allowSwitch)
        Mcu::getInstance()->touchSoundBeepMessage();
}

void HomeUi::on_goback_clicked()
{
    if(m_allowSwitch)
        Mcu::getInstance()->touchSoundBeepMessage();
}


/**
 * @brief HomeUi::6946旋转
 */
void HomeUi::on_imageRotate_2_clicked() {

    ui->imageRotate_2->setText(QString("%1").arg(m_rotate));
    setFpga[ImageRotate](m_rotate, 0);
    m_rotate++;
    if(m_rotate>=4)m_rotate = 0;
}

void HomeUi::on_pushButton_clicked() {
    ui->leftNavigation->setVisible(!ui->leftNavigation->isVisible());
    ui->rightNavigation->setVisible(!ui->rightNavigation->isVisible());
}

void HomeUi::on_pushButton_2_clicked() {
    on_pushButton_clicked();
}
